package org.feng.navigation.generator.gatewayimpl;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.feng.navigation.domain.generator.gateway.GeneratorClient;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO 类的描述
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年02月07日 16时56分
 */
@Slf4j
public abstract class BaseGeneratorClient implements GeneratorClient {

    protected final Map<String, Object> templateParamMap = new HashMap<>(16);

    protected abstract Template getTemplate();

    @Override
    public String process() {
        StringWriter stringWriter = new StringWriter();

        Template template = getTemplate();
        try {
            template.process(templateParamMap, stringWriter);
            return stringWriter.toString();
        } catch (TemplateException | IOException e) {
            String errorMsg = "模板渲染失败";
            log.error(errorMsg, e);
            return errorMsg;
        } finally {
            templateParamMap.clear();
            try {
                stringWriter.close();
            } catch (IOException e) {
                log.error("关闭字符串缓冲失败", e);
            }
        }
    }

    @Override
    public void addTemplateParam(String paramKey, Object paramValue) {
        templateParamMap.put(paramKey, paramValue);
    }

    @Override
    public void addTemplateParam(Map<String, Object> templateParamMap) {
        this.templateParamMap.putAll(templateParamMap);
    }
}
